//
//  CYABDetailVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/24.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYABDetailVController.h"
#import "CYAddressBookTVController.h"
#import "CYPerson.h"
#import "UIImageView+WebCache.h"
#import "CYPhoneView.h"
#import "CYDefaultRecordAO.h"
#import "CYDefaultRecordCell.h"
#import "CYCreditDetailTVController.h"
#import "CYStatisticsContentVC.h"
#import "CYStatisticsTopView.h"
#import "CYCallRecords.h"
#import "CYDialTool.h"
#import "CYABTool.h"
#import "CYMeHttpTool.h"
#import "CYEscape.h"
#import "CYJumpsTool.h"
#import "MBProgressHUD+MJ.h"
#import "CreditAddressBook-Swift.h"
#import "UIViewController+Category.h"
#import "CYCallRecord.h"
#import "UIInfomationView.h"
#include <CoreFoundation/CoreFoundation.h>
#import "CYCollectItem.h"
#import "CYCollectTool.h"
#import "CYShopViewController.h"
#import "CYLoginHttpTool.h"
#import "CYAddressBookTool.h"
#import "CYContacts.h"
#import "CNMutableContact+Extension.h"
#import "CNContact+LE.h"
#import "CYDatabase.h"

@interface CYABDetailVController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate,UIAlertViewDelegate, ABPersonViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *tbgView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;//头像
@property (weak, nonatomic) IBOutlet UILabel *companyLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *defaultViewW;//违约记录view宽度
@property (weak, nonatomic) IBOutlet UIButton *statisticsBtn;//统计按钮
@property (weak, nonatomic) IBOutlet UIButton *callHistoryBtn;//通话记录
@property (weak, nonatomic) IBOutlet UIButton *detailBtn;//详情
@property (weak, nonatomic) IBOutlet UIButton *defaultBtn;//违约记录
@property (weak, nonatomic) IBOutlet UIView *contentView;//内容
@property (weak, nonatomic) IBOutlet UIView *defaultView;
@property (weak, nonatomic) IBOutlet UIImageView *iconHand;
@property (weak, nonatomic) IBOutlet UILabel *noteLabel;
@property (weak, nonatomic) IBOutlet UILabel *shotnotelabel;

@property (strong, nonatomic) UIButton *selectedBtn;//选中的按钮

//@property (strong, nonatomic) CYStatisticsView *statisticsView;//统计显示内容
@property (strong, nonatomic) UIView *phoneView;//详情内容
@property (strong, nonatomic) CYCreditDetailTVController *credetail;//违约详情
@property (strong, nonatomic) CYStatisticsContentVC *statisVC;
@property (strong, nonatomic) CYCallRecords *calls;//通话记录view
//获取系统自带编辑信息
@property (nonatomic,strong) NSString *type; //积分兑换type

@end

@implementation CYABDetailVController

- (void)setPerson:(CYPerson *)person {
    _person = person;
}

- (void)setSelectedBtn:(UIButton *)selectedBtn {
    _selectedBtn = selectedBtn;
    
    _selectedBtn.layer.cornerRadius = 5;
    _selectedBtn.layer.masksToBounds = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"联系人详情";

    //短备注
    [self setupNote];
    
    //取消按钮
    [self setupCancelBtn];
    //显示
    [self setupPerson];
    
    //设置各个详情view
    [self setupView];
    
    //通讯录修改通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressBookImageChanged:) name:CYAddressBookChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phoneaddressBookChanged:) name:RHAddressBookExternalChangeNotification object:nil];
}

- (void)setupNote {
    NSString *note = (__bridge NSString *)ABRecordCopyValue(self.person.person.recordRef, kABPersonNoteProperty);
    self.noteLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:11.0f];
    self.noteLabel.textColor = [UIColor whiteColor];
    self.noteLabel.textAlignment = NSTextAlignmentCenter;
    self.noteLabel.layer.cornerRadius = 4.0f;
    self.noteLabel.layer.borderWidth = 0.8f;
    self.noteLabel.layer.borderColor = [UIColor whiteColor].CGColor;

    //self.noteLabel.numberOfLines = 2;
    if (!note || [note isEqualToString:@""]) {
        self.noteLabel.text = @"空";
        self.noteLabel.textColor = [UIColor grayColor];
        self.noteLabel.layer.borderColor = [UIColor grayColor].CGColor;
    } else {
        //self.noteLabel.text = [NSString stringWithFormat:@"备注:%@",note];
        self.noteLabel.text = note;
    }
}

- (void)setupPerson {
    RHPerson *rhPerson = self.person.person;
    self.nameLabel.text = rhPerson.name;
    self.companyLabel.text = rhPerson.organization;
    if (rhPerson.thumbnail) {
        [self.headImageView setImage:rhPerson.thumbnail];
    } else if (self.callRecord.callHistory.headImageName) {
        [self.headImageView setImage:[UIImage imageNamed:self.callRecord.callHistory.headImageName]];
    }
    
    self.headImageView.layer.cornerRadius = self.headImageView.width/2.f;
    self.headImageView.layer.masksToBounds = YES;
    
    self.tbgView.backgroundColor = CYNaviThemeColor;//头部背景
    
    //若为陌生号码或者失信人
    if (self.person.segmentTag != 1 && !self.person.add && self.person.segmentTag != 5) {
        self.headImageView.userInteractionEnabled = YES;
        [self.headImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setupImage:)]];
    } else {
        self.iconHand.hidden = YES;
    }
}

- (void)setupImage:(UITapGestureRecognizer *)tap {
    if (IOS8) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"设置头像" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(__unused UIAlertAction *action) {
            [self didDismissAlert:alert withButtonAtIndex:0];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(__unused UIAlertAction *action) {
            [self didDismissAlert:alert withButtonAtIndex:1];
        }]];
//        [alert addAction:[UIAlertAction actionWithTitle:@"头像DIY" style:UIAlertActionStyleDefault handler:^(__unused UIAlertAction *action) {
//            [self didDismissAlert:alert withButtonAtIndex:2];
//        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        
        [self presentViewController:alert animated:YES completion:nil];
    } else {
        UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机", @"从相册中选取", nil];
    
        [choiceSheet showInView:self.view];
    }
    
}

- (void)setupCancelBtn {
    if (self.person.pushTag != 1) {
        UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
        barBtn.tintColor = CYNaviTitleColor;
        self.navigationItem.leftBarButtonItem = barBtn;
    }
    
    if (self.person && !self.person.add && self.person.segmentTag != 5) {
        //编辑
        UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithTitle:@"更多" style:UIBarButtonItemStylePlain target:self action:@selector(edit:withEvent:)];
        barBtn.tintColor = CYNaviTitleColor;
        self.navigationItem.rightBarButtonItem = barBtn;
    } else if (self.person && self.person.add) {
        //保存陌生号码
        UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(addPerson)];
        barBtn.tintColor = CYNaviTitleColor;
        self.navigationItem.rightBarButtonItem = barBtn;
    }
}

#pragma mark - 添加陌生号码
/**
 *  添加陌生号码
 */
- (void)addPerson {
    [UIInfomationView showActionSheetInView:self.view WithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"新建联系人", @"添加到现有联系人"] clickAtIndex:^(NSInteger buttonIndex) {
        if (buttonIndex == CYIndexSecond) {//新建联系人
            RHPerson *rhPerson = self.person.person;
            NSString *phone = rhPerson.phoneNumbers.values.firstObject;
            
            CYContacts *contacts = [[CYContacts alloc] init];
            if (phone) {
                contacts.person = rhPerson;
#if IS_IOS9
                CNMutableContact *muContact = [[CNMutableContact alloc] init];
                muContact.imageData = nil;
                muContact.phones = @[phone];
                contacts.contact = muContact;
#endif
                
            }
            [CYAddressBookTool newPersonWithController:self person:contacts completion:^(id obj) {
                //联系人添加成功后的操作
                [self addSuccess:obj];
                [self.navigationController popViewControllerAnimated:NO];
                
            }];
        } else if (buttonIndex == CYIndexThird) {//添加到现有联系人
            [CYAddressBookTool addressBookUIPickerWithController:self edit:YES completion:^(id obj) {
                RHPerson *rhPerson = self.person.person;
                NSString *phone = rhPerson.phoneNumbers.values.firstObject;
                if (phone) {
                    CYContacts *contacts = [CYContacts contactsWithPerson:obj];
                    if (contacts.person) {
                        RHMutableMultiStringValue *value = contacts.person.phoneNumbers.mutableCopy;
                        [value addValue:phone withLabel:RHPersonPhoneIPhoneLabel];
                        contacts.person.phoneNumbers = value;
                    } else if (contacts.contact) {
#if IS_IOS9
                        CNMutableContact *muContact = contacts.contact.mutableCopy;
                        muContact.phones = @[phone];
                        contacts.contact = muContact;
#endif
                    }
                    [CYAddressBookTool newPersonWithController:self person:contacts completion:^(id obj) {
                        //联系人添加成功后的操作
                        [self addSuccess:obj];
                        [self.navigationController popViewControllerAnimated:NO];
                    }];
                }
            }];
        }
    }];
}

/**
 *  联系人添加成功后的操作
 */
- (void)addSuccess:(id)obj {
    CYContacts *contacts = [CYContacts contactsWithPerson:obj];
    if (contacts.person) {
        self.callRecord.callHistory.name = contacts.person.name;
        self.callRecord.callHistory.recordID = contacts.person.recordID;
    } else if (contacts.contact) {
#if IS_IOS9
        self.callRecord.callHistory.name = contacts.contact.name;
        self.callRecord.callHistory.identifier = contacts.contact.identifier;
#endif
        
    }
    //将动物头像去除掉
    self.callRecord.callHistory.headImageName = nil;
    [self.callRecord.callHistory update];
    //发出通知更新通话记录显示
    [CYNotificationCenter postNotificationName:CYCallRecordChangeNotification object:nil];
}

/**
 *  取消按钮方法
 */
- (void)cancel {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 收藏，修改
/**
 *  收藏与修改
 */
- (void)edit:(UIBarButtonItem *)barButtonItem withEvent:(UIEvent *)event {
    //创建action
    [UIInfomationView showActionSheetInView:self.view WithTitle:nil cancelButtonTitle:@"返回" destructiveButtonTitle:nil otherButtonTitles:@[@"修改"] clickAtIndex:^(NSInteger buttonIndex) {
          if (buttonIndex == 1) {//修改
              [self changeBtn];
          }
          else if (buttonIndex == 2) {//收藏
             // [self DeleteBtn];
          }
    }];
}

- (void)changeBtn {
    
    ABPersonViewController *personController = [[ABPersonViewController alloc]init];
    [self.navigationController pushViewController:personController animated:YES];
    
    personController.displayedPerson = self.person.person.recordRef;
    //设置代理
    personController.personViewDelegate = self;
    
    [personController setDisplayedPerson:self.person.person.recordRef];
    
    [personController setEditing:YES];
    
    [personController setAllowsActions:YES];
    
    [personController setAllowsEditing:YES];
}

#pragma mark - ABPersonViewControllerDelegate
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
//#warning 没有调用
    //发出通知更新通话记录显示
    [CYNotificationCenter postNotificationName:CYCallRecordChangeNotification object:nil];
    return YES;
}

/**
 *  收藏
 */
-(void)DeleteBtn {
    CYCollectItem *item = [[CYCollectItem alloc]init];
    item.phone = self.person.phone ;
    item.name = self.person.name ;
    item.thumbnailLocal  = self.headImageView.image ;
    item.headImageName = self.callRecord.callHistory.headImageName ;
    [[CYCollectTool sharedCollectTool] collectItem:item];
    
    //发出通知收藏成功
    [[NSNotificationCenter defaultCenter] postNotificationName:CYCollectionNotification object:nil userInfo:nil];

//      UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
//    
//    // Create the actions.
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//        NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
//    }];
//    
//    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//        NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
//    }];
//    
//    // Add the actions.
//    [alertController addAction:cancelAction];
//    [alertController addAction:otherAction];
}

#pragma mark - ABNewPersonViewController代理
//完成新增（点击取消和完成时候调用）
-(void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person {
    
    //关闭模态视图窗口
    [self dismissViewControllerAnimated:YES completion:nil];
    [self performSelector:@selector(update) withObject:nil afterDelay:0.5];
}

-(void)update {
    NSString *note = (__bridge NSString *)ABRecordCopyValue(self.person.person.recordRef, kABPersonNoteProperty);
    //self.noteLabel.text = [NSString stringWithFormat:@"备注 :%@",note];
    self.noteLabel.text = note;
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        //对图片进行压缩
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
//        CYLog(@"oldH:%f---oldW:%f", portraitImg.size.height, portraitImg.size.width);
        UIImage *newImage = [UIImage imageWithImage:portraitImg scaledToSize:(CGSize){200, 200}];
//        CYLog(@"height---%f, with---%f", newImage.size.height, newImage.size.width);
        RHPerson *person = self.person.person;
        [person setImage:newImage];
        [person save];
        [self.headImageView setImage:newImage];
        [MBProgressHUD showSuccess:@"修改成功"];
        
    }];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self didDismissAlert:nil withButtonAtIndex:buttonIndex];
}

/**
 *  点击相册界面取消时调用
 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)naviBtnClick:(id)sender {
    UIButton *btn = sender;
    if (self.selectedBtn.tag == btn.tag) {
        return;
    }
    
    //选中切换背景
    self.selectedBtn.backgroundColor = [UIColor clearColor];
    btn.backgroundColor = CYNaviThemeColor;
    self.selectedBtn = btn;
    
    [[self.contentView.subviews firstObject] removeFromSuperview];
    
    switch (btn.tag) {
        case 0:
            [self.contentView addSubview:self.statisVC.view];
            [self.statisVC.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
            break;
        
        case 1:
            [self.contentView addSubview:self.calls];
            [self.calls autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
            break;
        
        case 2:
            [self.contentView addSubview:self.phoneView];
            [self.phoneView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
            break;
        
        case 3:
            [self.contentView addSubview:self.credetail.view];
            [self.credetail.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
            break;
            
        default:
            break;
    }
}

- (void)setupView {
    CGFloat with = CYScreeSize.width;
    
    //电话详情view
    UIView *view = [[UIView alloc] initWithFrame:(CGRect){CGPointZero, self.contentView.frame.size}];
    RHPerson *person = self.person.person;
    NSArray *phones = [CYABTool formatPhoneNumbers:person.phoneNumbers.values];
    CGFloat y = 20;
    for (NSString *phone in phones) {
        CYPhoneView *phoneView = [CYPhoneView phoneView];
        phoneView.phone = phone;
        phoneView.name = person.name;
        phoneView.person = self.person;
        CGFloat phoneViewX = (with - phoneView.frame.size.width)/2;
        phoneView.frame = (CGRect){CGPointMake(phoneViewX, y), phoneView.frame.size};
        [view addSubview:phoneView];
        y += phoneView.frame.size.height;
    }
    self.phoneView = view;
    
    //统计view
    CYStatisticsContentVC *statiVC = [[CYStatisticsContentVC alloc] init];
    statiVC.person = self.person;
    self.statisVC = statiVC;
    [self addChildViewController:statiVC];
    
    UIView *statisView = [[UIView alloc] init];
    statisView.backgroundColor = [UIColor clearColor];
    CYStatisticsTopView *topview = [CYStatisticsTopView topView];
    statiVC.topView = topview;
    [statisView addSubview:statiVC.view];
    [statiVC didMoveToParentViewController:self];
    
    //通话记录view
    CYCallRecords *calls = [CYCallRecords loadFromNibUsingClassName];
    calls.callRecords = [self loadCallHistory:self.person.phones];
    self.calls = calls;
    
    //若是失信联系人，显示失信人展示view
    if (self.person.segmentTag == 1) {
        //违约记录view
        CYDefaultRecordAO *defr = [[CYDefaultRecordAO alloc] init];
        defr.pushTag = 3;
        defr.defaultRecordId = self.person.simpleRecord.recordId;
        CYCreditDetailTVController *credetail = [[CYCreditDetailTVController alloc] init];
        credetail.defr = defr;
        credetail.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self addChildViewController:credetail];
        self.credetail = credetail;
        [self selectedTo:self.defaultBtn selectedView:credetail.view];
        [credetail didMoveToParentViewController:self];
    } else if (self.person.segmentTag == 3) {
        self.defaultViewW.constant = 0;//隐藏失信人展示view
        //选中第1个按钮
        [self selectedTo:self.statisticsBtn selectedView:self.statisVC.view];
    } else if (self.person.segmentTag == 4) {
        self.defaultViewW.constant = 0;//隐藏失信人展示view
        //选中第1个按钮
        [self selectedTo:self.callHistoryBtn selectedView:self.calls];
    } else {
        self.defaultViewW.constant = 0;//隐藏失信人展示view
        //默认选中第三个按钮
        [self selectedTo:self.detailBtn selectedView:self.phoneView];
    }
}


/**
 *  加载通话记录
 */
- (NSArray *)loadCallHistory:(NSArray *)phones {
    NSMutableArray *calls = [NSMutableArray array];
    for (NSString *phone in phones) {
        NSArray *arr = [[CYDatabase sharedDatabase] callHistorysWithParam:@{@"phone": phone}];
        if (arr && arr.count) {
            [calls addObjectsFromArray:arr];
        }
    }
    return calls;
}

/**
 *  设置选中按钮
 *
 *  @param from
 *  @param to
 *  @param view
 */
- (void)selectedTo:(UIButton *)to selectedView:(UIView *)view {
    self.selectedBtn.backgroundColor = [UIColor clearColor];
    to.backgroundColor = CYNaviThemeColor;
    self.selectedBtn = to;
    [self.contentView addSubview:view];//默认显示统计view
    [view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
}

/**
 *  UIAlertController dismiss
 *
 *  @param alertView
 *  @param buttonIndex
 */
- (void)didDismissAlert:(id)alertView withButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [CYMeHttpTool imageFromCameraWithController:self Delegate:self completion:^{
            
        }];
    } else if (buttonIndex == 1) {
        [CYMeHttpTool imageFromPhotoLibraryWithController:self Delegate:self completion:^{
            
        }];
    } else if (buttonIndex == 2) {
        CYBlackAppImageVC *blackApp = [CYBlackAppImageVC xc_loadFromNibUsingClassName];
        blackApp.person = self.person;
        blackApp.callRecord = self.callRecord;
        [self.navigationController pushViewController:blackApp animated:YES];
        
//        [CYABTool imageSelectOneWithParams:@{@"name": [CYEscape escapeWithString:@"李学超"]} success:^(NSArray *defrs) {
//            
//        } failure:^(NSError *error) {
//            
//        }];
    }
   
}

//- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
//    return NO;
//}

#pragma mark - ABPersonViewController 查看更多信息并编辑
//- (void)systemAddressBook {
    
    
//    ABAddressBookRef abRef = ABAddressBookCreate();
    
   
//    ABAddressBookRequestAccessWithCompletion(self.addressBookRef, ^(bool granted, CFErrorRef error) {
//        if (granted) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self getContactsFromAddressBook];
//            });
//        } else {
//            // TODO: Show alert
//        }
//    });
    
//}

#pragma mark - 监听

/**
 *  监听系统通讯录的更改
 *
 *  @param notifi
 */

//详情头像通知
- (void)addressBookImageChanged:(NSNotification *)notifi {
    NSString *imageUrl = notifi.userInfo[CYAddressBookImageKey];
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
    NSString *type = @"2";
    [self requestFirst:type];
    
}

-(void)requestFirst:(NSString *)type{
    
    [CYABTool jfshopWithType:@"2" success:^(NSString *message) {
        
    } failure:^(NSError *error) {
        
    }];

}

//联系人详情信息通知
- (void)phoneaddressBookChanged:(NSNotification *)notifi{
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    
    RHPerson *phoneperson = [self.person.person.addressBook personForABRecordID:self.person.person.recordID];
    self.person.person = phoneperson;
    //电话号码
    CGFloat with = CYScreeSize.width;
    UIView *view = [[UIView alloc] initWithFrame:(CGRect){CGPointZero, self.contentView.frame.size}];
    NSArray *phones = [CYABTool formatPhoneNumbers:phoneperson.phoneNumbers.values];
    CGFloat y = 20;
    for (NSString *phone in phones) {
        CYPhoneView *phoneView = [CYPhoneView phoneView];
        phoneView.phone = phone;
        phoneView.name = phoneperson.name;
        phoneView.person = self.person;
        CGFloat phoneViewX = (with - phoneView.frame.size.width)/2;
        phoneView.frame = (CGRect){CGPointMake(phoneViewX, y), phoneView.frame.size};
        [view addSubview:phoneView];
        y += phoneView.frame.size.height;
    }
    self.phoneView = view;
    
    //若选择的是电话view则更新view显示
    if (self.selectedBtn.tag == CYIndexThird) {
        [[self.contentView.subviews firstObject] removeFromSuperview];
        [self.contentView addSubview:self.phoneView];
        [self.phoneView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
    }
    //头像
    if (phoneperson.thumbnail) {
        self.headImageView.image = phoneperson.thumbnail;
    }
    //群组
    self.companyLabel.text = phoneperson.organization;
    //姓名
    self.nameLabel.text = phoneperson.name;
    //备注
    if (phoneperson.note && phoneperson.note.length) {
        //self.noteLabel.text = [NSString stringWithFormat:@"备注:%@",phoneperson.note];
        self.noteLabel.text = phoneperson.note;
        CYLog(@"备注已修改");
        self.noteLabel.textColor = [UIColor whiteColor];
        self.noteLabel.layer.borderColor = [UIColor whiteColor].CGColor;
    } else {
        CYLog(@"备注为空");
        self.noteLabel.text = @"空";
        self.noteLabel.textColor = [UIColor grayColor];
        self.noteLabel.layer.borderColor = [UIColor grayColor].CGColor;
    }
}

#pragma mark - 数据刷新
/**
 *  刷新数据显示
 */
- (void)reloadView {
    
    RHPerson *phoneperson = [self.person.person.addressBook personForABRecordID:self.person.person.recordID];
    self.person.person = phoneperson;
    self.person.add = NO;
    [self clear];
    //短备注
    [self setupNote];
    //取消按钮
    [self setupCancelBtn];
    //显示
    [self setupPerson];
    //设置各个详情view
    [self setupView];
}

- (void)clear {
    [self.phoneView removeFromSuperview];
    [self.calls removeFromSuperview];
}

/**
 *  设置navigationBar阴影
 */
- (void)setupNaviBar {
}

- (void)viewWillDisappear:(BOOL)animated {
//        [self setupNaviBar];
    
//        UIGestureRecognizer *a = self.navigationController.interactivePopGestureRecognizer;
//        CGPoint p = [a locationInView:self.view];
//        CYLog(@"X:%f, Y:%f", p.x, p.y);
    [super viewWillDisappear:animated];
}

- (void)dealloc {
    CYLog(@"通讯录详细页面销毁");
    [CYNotificationCenter removeObserver:self];
}



@end
